package hibari.server.servlet;

import hibari.server.lib.AdminLog;
import hibari.server.lib.MultiPartRequest;
import hibari.server.operations.EditWeek;
import hibari.server.operations.NewWeek;
import hibari.server.operations.Operation;
import hibari.server.operations.RemoveWeek;
import hibari.server.operations.RestoreWeek;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Edit extends HttpServlet {

    private Map<String, Class<? extends Operation>> operationFactories = new HashMap<String, Class<? extends Operation>>();

    public Edit() {
        this.operationFactories.put("newWeek", NewWeek.class);
        this.operationFactories.put("editWeek", EditWeek.class);
        this.operationFactories.put("removeWeek", RemoveWeek.class);
        this.operationFactories.put("restoreWeek", RestoreWeek.class);
    }

    /**
     * 
     */
    private static final long serialVersionUID = 3233616155257123027L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MultiPartRequest mpr = new MultiPartRequest(request);
        String operation = mpr.getParameter("operation");

        Operation opInstance = getOperationInstance(response, mpr, operation);
        if (opInstance != null) {
            opInstance.doOperation();
        } else {
            AdminLog.get(mpr).addError(operation + "에 대한 명령을 찾지 못했습니다.");
        }

        AdminLog.get(request.getSession()).update(request.getSession());

        String callback = mpr.getParameter("callback");
        if (callback != null) {
            response.sendRedirect(callback);
        } else {
            response.sendRedirect("/Admin/index.jsp");
        }
    }

    private Operation getOperationInstance(HttpServletResponse response, MultiPartRequest mpr, String operation) {
        Operation opInstance = null;
        try {
            Class<? extends Operation> opType = this.operationFactories.get(operation);
            if (opType == null) {
                return null;
            }
            Constructor<? extends Operation> constructor = opType.getConstructor(MultiPartRequest.class, HttpServletResponse.class);
            if (constructor == null) {
                System.err.print("컨스트럭터 불량");
                return null;
            }
            opInstance = constructor.newInstance(mpr, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return opInstance;
    }
}
